﻿using System;
using System.Collections.Generic;
using UnityEngine;
namespace GX
{
    public class EventManagerService : EventDispatcher, IEventManager
    {
        static readonly int TypeHashCode_PostEventInfo = typeof(PostEventInfo).GetHashCode();
        class PostEventInfo
        {
            public int type;
            public object body;
            public string name;
            public int invokeFrame;
            public void Reset()
            {
                type = 0;
                body = null;
                name = string.Empty;
            }
        }


        readonly Queue<PostEventInfo> _eventQueue = new Queue<PostEventInfo>();
        readonly EventDispatcher _dispatcher = new EventDispatcher();
        int _tickID;
        public void OnRegister()
        {
            PoolManager.SetCapacity(TypeHashCode_PostEventInfo, 16);
        }
        public void PostEvent(int type, object body = null,string name=null)
        {
            PostEventInfo eventInfo = PoolManager.Get<PostEventInfo>();
            eventInfo.type = type;
            eventInfo.body = body;
            eventInfo.name = name;
            eventInfo.invokeFrame = Time.frameCount;
            _eventQueue.Enqueue(eventInfo);
            if (_eventQueue.Count == 1)
            {
                _tickID = TickManager.Repeat(1, 0, OnTick);
            }
        }
        void OnTick(ITickable ticker)
        {
            int curFrame = TickManager.frameCount;
            PostEventInfo eventInfo = null;
            int len = _eventQueue.Count;
            while (len != 0)
            {
                eventInfo = _eventQueue.Peek();
                if (null == eventInfo || curFrame == eventInfo.invokeFrame)
                    break;
                _eventQueue.Dequeue();
                SendEvent(eventInfo.type, eventInfo.body, eventInfo.name);
                PoolManager.Release(eventInfo);
                --len;
            }
            if (0 == len)
                TickManager.Cancel(_tickID);
        }
    }
}